<?php
/**
 * Kcontroller
 * @author Sokha RUM
 *
 */
class Kcontroller extends CI_Controller {
	protected $k_page_status = "";
	protected $k_application_title = "khawin - Accounting";
	
	/*
	protected $email_config = Array(
		  'protocol' => 'sendmail',
          'mailpath' => '/usr/sbin/sendmail',
		  'mailtype' => 'text',
		  'charset' => 'utf-8',
		  'wordwrap' => TRUE
		);
    */  
      
    protected $email_config = Array(
		  'protocol' => 'smtp',
		  'smtp_host' => 'ssl://smtp.gmail.com',
		  'smtp_port' => 465,
		  'smtp_user' => 'rum.sokha123@gmail.com',
		  'smtp_pass' => 'linadany',
		  'mailtype' => 'text',
		  'charset' => 'utf-8',
		  'wordwrap' => TRUE
	);
	
	/**
	 * Constructor of this controller
	 */
    function __construct() {
    	parent::__construct();
    	$this->initController();
    }
    
    function current_company_status() {
    	$status = Kconstant::COM_TEST;
    	$user = Ksession::getUser();
    	if ($user["grp_id"] == Kconstant::USER_SYSTEM) {
    		$status = Kconstant::COM_CONTRACTED;
    	} else if ($user["company"]["com_status"] == Kconstant::COM_CONTRACTED) {
    		$status = Kconstant::COM_CONTRACTED;
    	} else {
    		$cur_date = date("Y-m-j G:i:s");
    		$last_90days = date("Y-m-d H:i:s", strtotime ( "-".Kconstant::APP_FREE_DAYS." day" . $cur_date ));
    		if (strcmp($user["company"]["creation_date"], $last_90days) < 0) {
    			$status = Kconstant::COM_EXPIRED;
    		} else {
    			$status = Kconstant::COM_TEST;
    		}
    	}
    	return $status;
    }
    private function initController() {
    	$this->k_page_status = isset($_REQUEST["k_page_status"]) ? $_REQUEST["k_page_status"] : "";
        $CI =& get_instance();
		define("CHAR_SET", $CI->config->item("charset"));
		$this->load->helper("html");
        $this->load->helper('url');
        $this->load->helper("karm");
        require_once BASEPATH.'core/Model.php';
        require_once APPPATH.'libraries/Kmodel.php';
        require_once APPPATH.'libraries/Ksession.php';
        //require_once APPPATH.'libraries/Translation.php';
        require_once APPPATH.'libraries/Kencryption.php';
        require_once APPPATH.'libraries/Kconstant.php';
        $session_status = Ksession::initializeSession();
        //$this->init_karm();
        $this->controlUser($session_status);
        //$this->load_translation(array("general"));
    }
    /*
    private function init_karm() {
    	if (!isset($_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]) || count($_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]) <= 1) {
	    	$_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"] = array();
	    	$this->load->model("karmmodel");
	    	$_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]["LANGUAGE_DEF"] = $this->karmmodel->getDefaultLanuage(Kconstant::K_APPLICATION_ID);
	    	$_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]["LANGUAGE_LIST"] = $this->karmmodel->getLanguages(Kconstant::K_APPLICATION_ID);
	    }
	    
	    
	    if (!isset($_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]["LANGUAGE_SELECTED"])) {
	    	$_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]["LANGUAGE_SELECTED"] = $_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]["LANGUAGE_DEF"]; 
	    }
	    //var_dump($_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]);
	    //unset($_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"]);
    }
    */
    
    private function controlUser($session_status) {
    	$uri = trim(uri_string(), "/");
    	
    	$user = Ksession::getUser();
    	//$this->load_language("common");
        if ($user != null) {
        	if ($session_status == 1) {
	    		Ksession::destroy();
	    		Ksession::initializeSession();
	    		Ksession::setFlash("message", "Session is expired");
	    		redirect(site_url(""));
	    		return;
    	    } 
            if ($uri == "" || $uri == "main/login") {
            	redirect("main/home");
            	return;
            }
        } else if ($uri == "" || $uri == "main/submitlogin" 
                || $uri=="main/signup" || $uri=="main/submitsignup" 
                || $uri == "main/forgotpwdsubmit" || $uri == "main/pwdsent" || $uri == "main/login" || $uri == "kcaptcha"
                || $uri=="main/language") {
            // DO NOTHING
        } else {
           redirect(site_url(""));
           return;
        }
    }
    
    protected function getOrder() {
    	$order = null;
        if (isset($_GET["order"])) {
   	   	    $error_reporting = error_reporting(error_reporting() ^ E_NOTICE);
	   	    $order = unserialize(Kencryption::decrypt($_GET["order"]));
	   	    error_reporting($error_reporting);
        }
        if ($order == null || !is_array($order)) {
           return null;
        }
        return $order;
    }
    /**
	 * Loading translation
	 * @param array $pages
	 */
	function load_translation($pages = array()) {
		$karm = $_SESSION[Ksession::SESSION_KEY][Ksession::SESSION_APP]["KARM"];
		if (is_array($pages) && count($pages) > 0) {
			$this->load->model("karmmodel");
		    $object_translation = $this->karmmodel->getObjects($pages, $karm["LANGUAGE_LIST"][$karm["LANGUAGE_SELECTED"]]);
		    Translation::getInstance()->merge_object($object_translation);
		}
	} 
	
    
    public function validatedate_check($str) {
    	if ($str == "") {
    		return true;
    	}
	    //if ( ereg("([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})", $str) ) {
    	//if ( preg_match("/^([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})$/", $str) ) {
	   $arr = explode("/",$str);// splitting the array
	   if (count($arr) == 3 && 
	       is_nint($arr[0]) && 
	       is_nint($arr[1]) &&
	       is_nint($arr[2])) {
	       $yy = $arr[2];         //first element of the array is year
	       $mm = $arr[1];         //second element is month
	       $dd = $arr[0];         //third element is days
	       if( checkdate($mm, $dd, $yy) ) {
	          return true;
	       } else {
	       	  $this->form_validation->set_message('validatedate_check', "Le champ %s n'est pas bon format.");
	       	  return false;
	       }
	   } else {
	       $this->form_validation->set_message('validatedate_check', "Le champ %s n'est pas bon format.");
	       return false;
	   }
    }
    public function validatetime_check($str) {
    	$arr = explode(":", $str);
    	if (count($arr) != 2) {
    		$this->form_validation->set_message('validatetime_check', "Le champ %s n'est pas bon format.");
	        return false;
    	}
    	$hh = $arr[0];
    	$mm = $arr[1];
    	if(!is_nint($hh) || !is_nint($mm)) {
    		$this->form_validation->set_message('validatedate_check', "Le champ %s n'est pas bon format.");
	        return false;
    	} else if ((int) $hh > 24 || (int) $mm > 59) {
    		$this->form_validation->set_message('validatedate_check', "Le champ %s n'est pas bon format.");
	        return false;
    	} else if (mktime((int) $hh, (int) $mm) === FALSE) {
    		$this->form_validation->set_message('validatedate_check', "Le champ %s n'est pas bon format.");
	        return false;
    	}
    	return true;
    }     
    public function load_language($filename, $language=null) {
    	if ($language == null) {
    		$this->lang->load($filename);
    	} else {
    		$this->lang->load($filename, $language);
    	}
    }
}
?>